package com.example.androidproject.novel.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.androidproject.R;

import java.util.ArrayList;
import java.util.List;

public class NovelCatalogueAdapter extends RecyclerView.Adapter<NovelCatalogueAdapter.CatalogueViewHolder> {
    private final Context mContext;
    private List<String> catalogList;
    private final LayoutInflater layoutInflater;
    private ItemOnClickListener itemOnClickListener;

    public NovelCatalogueAdapter(Context mContext, List<String> catalogList) {
        this.mContext = mContext;
        this.catalogList = catalogList;
        layoutInflater = LayoutInflater.from(mContext);


    }

    @NonNull
    @Override
    public CatalogueViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new CatalogueViewHolder(layoutInflater.inflate(R.layout.catalogue_item, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull CatalogueViewHolder holder, int position) {
        holder.tv_catalog.setText(catalogList.get(position));
        holder.tv_catalog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                itemOnClickListener.onClick(position);
            }
        });
    }

    @Override
    public int getItemCount() {
        if (catalogList == null) return 0;
        return catalogList.size();
    }


    class CatalogueViewHolder extends RecyclerView.ViewHolder {
        public TextView tv_catalog;

        public CatalogueViewHolder(@NonNull View itemView) {
            super(itemView);
            this.tv_catalog = itemView.findViewById(R.id.tv_catalog);
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    public void refresh(List<String> List) {
        if (this.catalogList == null)
            this.catalogList = new ArrayList<>();
        this.catalogList.addAll(List);
        notifyDataSetChanged();
    }

    public interface ItemOnClickListener {
        void onClick(int position);
    }

    public void setItemOnClickListener(ItemOnClickListener itemOnClickListener) {
        this.itemOnClickListener = itemOnClickListener;
    }
}
